package com.xiaohe.gulimall.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xiaohe.common.utils.R;
import com.xiaohe.gulimall.feign.ProductFeignService;
import com.xiaohe.gulimall.interceptor.CartInterceptor;
import com.xiaohe.gulimall.service.CartService;
import com.xiaohe.gulimall.seckill.vo.Cart;
import com.xiaohe.gulimall.seckill.vo.CartItem;
import com.xiaohe.gulimall.seckill.vo.SkuInfoVo;
import com.xiaohe.gulimall.seckill.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private final String CART_PREFIX ="gulimall:cart";
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        //将商品信息添加到购物车
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if(StringUtils.isEmpty(res)){
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询要添加的商品信息
                R info = productFeignService.info(skuId);
                SkuInfoVo skuInfo = (SkuInfoVo) info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(skuInfo.getPrice());
            }, executor);
            CompletableFuture<Void> getSkuSaleAttr = CompletableFuture.runAsync(() -> {
                //远程查找sku的组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);
            //等待所有的异步任务全部完成
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttr).get();
            String jsonString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),jsonString);
            return cartItem;
        }else {
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 获取购物车的购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        CartItem item = JSON.parseObject(res, CartItem.class);

        return item;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        //判断登录还是登录
        Cart cart = new Cart();
        UserInfoTo userInfo = CartInterceptor.getUserInfo();
        if(userInfo.getUserId()!=null){
            //1、登录
            String userKey =CART_PREFIX +userInfo.getUserId();
            String tempKey =CART_PREFIX+userInfo.getUserKey();
            BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(userKey);
            List<CartItem> cartItems = getCartItems(tempKey);
            if(cartItems!=null&&cartItems.size()>0){
                //临时购物车不为空，合并
                for (CartItem cartItem : cartItems) {
                    addToCart(cartItem.getSkuId(), cartItem.getCount());
                }
                //清空临时购物车
                clearCart(tempKey);
            }
            //获取登录后购物车数据[包括合并过来之后的数据]
            List<CartItem> cartItems1 = getCartItems(userKey);
            cart.setCartItems(cartItems1);
        }else {
            //2、未登录
            String userKey =CART_PREFIX +userInfo.getUserKey();
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setCartItems(cartItems);
        }

        return cart;
    }


    //清空购物车
    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String jsonString = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),jsonString);

    }

    //修改购物项的数量
    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId);
    }

    @Override
    public List<CartItem> getUserItems() {
        //获取购物车的所有购物项
        UserInfoTo userInfo = CartInterceptor.getUserInfo();
        System.out.println("getUserItems的线程为"+Thread.currentThread().getId());
        if(userInfo.getUserId() == null){
            return null;
        }else {
            String cartKey = CART_PREFIX + userInfo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().filter(item -> {
                return item.getCheck();
            }).map(item->{
                //更新价格
                BigDecimal price = productFeignService.getPrice(item.getSkuId());
                item.setPrice(price);
                return item;
            }).collect(Collectors.toList());

            return collect;
        }
    }

    //获取要操作的购物车
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfo = CartInterceptor.getUserInfo();
        String cartKey ="";
        //得到用户信息
        if(userInfo!=null){
            //登录用户
            cartKey=CART_PREFIX+userInfo.getUserId();
        }else {
            //临时用户
            cartKey=CART_PREFIX+userInfo.getUserKey();
        }
        //获取购物车信息
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        return operations;
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if(values!=null && values.size()>0 ){
            List<CartItem> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem item = JSON.parseObject(str, CartItem.class);
                return item;
            }).collect(Collectors.toList());
           return collect;
        }else {
            return null;
        }
    }

}
